//
//  CommentsTableViewController.m
//  Sydeny
//
//  Created by Rainbow on 8/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CommentsTableViewController.h"
#import "ServiceHelper.h"
#import "SDCommentCell.h"
#import "UtilHelper.h"
#import "AddCommentViewController.h"
#import "CacheData.h"

@implementation CommentsTableViewController

@synthesize shopId = _shopId;
@synthesize commentsTableView;

-(id)initWithShopId:(NSString *)aId
{
    self = [super init];
    if (self) {
        comments = [[NSMutableArray alloc] init];
        self.shopId = aId;
    }
    return self;
}

- (void)dealloc
{
    self.shopId = nil;
    [commentsTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.title = @"评论列表";
    
    
    UIButton *backBtn = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)] autorelease];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back_btn.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(tapBackBtn) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
    backBtn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] initWithCustomView:backBtn] autorelease];
    self.navigationItem.leftBarButtonItem = backItem;
    
    UIButton *rightBtn = [[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)] autorelease];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"right_btn.png"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(tapCommentBtn) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setTitle:@"评论" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    UIBarButtonItem *rightItem = [[[UIBarButtonItem alloc] initWithCustomView:rightBtn] autorelease];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setCommentsTableView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[ServiceHelper sharedService] requestServerForMethod:SydenyRequestGetComments WithParameters:[NSDictionary dictionaryWithObject:_shopId forKey:@"shopid"] AndCallBackScope:self AndSuccessSel:@"getCommentsSuccess:" AndFailedSel:@"getCommentsFailed:"];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [comments count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
        UILabel *refreshLabel = [[[UILabel alloc] initWithFrame:CGRectMake(75, 5 , 150, 20)] autorelease];
        refreshLabel.text = @"点击刷新...";
        refreshLabel.textAlignment = UITextAlignmentCenter;
        [cell.contentView addSubview:refreshLabel];
        
        UIImageView *refreshIcon = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refresh_icon.png"]] autorelease];
        refreshIcon.frame = CGRectMake(75, 7, 15, 15);
        [cell.contentView addSubview:refreshIcon];
        
        return cell;
    }
    
    Comment *comment = [comments objectAtIndex:indexPath.row - 1]; 
    
    static NSString *CellIdentifier = @"Cell";
    
    SDCommentCell *cell = (SDCommentCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[SDCommentCell alloc] initWithComment:comment reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else
    {
        [cell updateWithComment:comment];
    }
    // Configure the cell...
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
         [[ServiceHelper sharedService] requestServerForMethod:SydenyRequestGetComments WithParameters:[NSDictionary dictionaryWithObject:_shopId forKey:@"shopid"] AndCallBackScope:self AndSuccessSel:@"getCommentsSuccess:" AndFailedSel:@"getCommentsFailed:"];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 30;
    }
    else
    {
        Comment *comment = [comments objectAtIndex:indexPath.row - 1]; 
        NSInteger contentHeight = [comment.content sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(280, 200) lineBreakMode:UILineBreakModeWordWrap].height;
        return contentHeight + 50;
    }
}

-(void)getCommentsSuccess:(NSObject *)result
{
    [comments removeAllObjects];
    NSArray *commentArray = [(NSDictionary *)result objectForKey:@"comments"];
    for (NSDictionary *commentDic in commentArray) {
        Comment *comment = [[[Comment alloc] init] autorelease];
        comment.commentId = [UtilHelper getStringValue:[commentDic objectForKey:@"comment_id"]];
        comment.username = [UtilHelper getStringValue:[commentDic objectForKey:@"nickname"]];
        comment.content = [UtilHelper getStringValue:[commentDic objectForKey:@"content"]];
        comment.timestamp = [UtilHelper getStringValue:[commentDic objectForKey:@"createtime"]];
        [comments addObject:comment];
    }
    [commentsTableView reloadData];
}

-(void)getCommentsFailed:(NSObject *)result
{
    
}

-(void)tapBackBtn
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)tapCommentBtn
{
    if ([CacheData sharedData].user.userId != nil) {
        
        AddCommentViewController *addCommentViewController = [[AddCommentViewController alloc] init];
        addCommentViewController.shopId = self.shopId;
        [self.navigationController pushViewController:addCommentViewController animated:YES];
        [addCommentViewController release];
    }
    
    else
    {
        LoginViewController *loginViewController = [[LoginViewController alloc] init];
        loginViewController.delegate = self;
        UINavigationController *tempNavigationController = [[UINavigationController alloc] initWithRootViewController:loginViewController];
        [self.navigationController presentModalViewController:tempNavigationController animated:YES];
        [tempNavigationController release];
        [loginViewController release];
    }
}

-(void)LoginSuccess
{
    AddCommentViewController *addCommentViewController = [[AddCommentViewController alloc] init];
    addCommentViewController.shopId = self.shopId;
    [self.navigationController pushViewController:addCommentViewController animated:YES];
    [addCommentViewController release];
}

@end
